import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // 检查是否是管理员权限问题
      const currentPath = window.location.pathname
      if (currentPath.includes('/admin')) {
        // 如果在管理页面遇到401，可能是权限不足，不要自动退出
        console.warn('管理员权限不足')
        return Promise.reject(error)
      } else {
        // 其他情况下清除token并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

export default api

// 用户相关API
export const authAPI = {
  // 用户注册
  register: (userData: {
    username: string
    email: string
    password: string
    first_name?: string
    last_name?: string
  }) => api.post('/auth/register/', userData),

  // 用户登录
  login: (credentials: { username: string; password: string }) =>
    api.post('/auth/login/', credentials),

  // 用户登出
  logout: () => api.post('/auth/logout/'),

  // 获取当前用户信息
  getCurrentUser: () => api.get('/auth/user/'),
}

// 电影相关API
export const movieAPI = {
  // 获取电影列表
  getMovies: (params?: { search?: string; genre?: string; page?: number; page_size?: number }) =>
    api.get('/movies/', { params }),

  // 获取电影详情
  getMovie: (id: number) => api.get(`/movies/${id}/`),

  // 获取电影类型
  getGenres: () => api.get('/genres/'),

  // 获取热门电影
  getPopularMovies: (num?: number) =>
    api.get('/popular/', { params: { num } }),
}

// 评分相关API
export const ratingAPI = {
  // 获取用户评分列表
  getRatings: () => api.get('/ratings/'),

  // 创建评分
  createRating: (ratingData: { movie: number; rating: number }) =>
    api.post('/ratings/', ratingData),

  // 更新评分
  updateRating: (id: number, ratingData: { rating: number }) =>
    api.put(`/ratings/${id}/`, ratingData),

  // 删除评分
  deleteRating: (id: number) => api.delete(`/ratings/${id}/`),
}

// 推荐相关API
export const recommendationAPI = {
  // 获取推荐电影
  getRecommendations: (params?: {
    algorithm?: 'user_based' | 'item_based' | 'content_based' | 'hybrid'
    num?: number
    page?: number
    page_size?: number
  }) => api.get('/recommendations/', { params }),

  // 获取用户统计信息
  getUserStats: () => api.get('/user/stats/'),
}

// 留言相关API
export const commentAPI = {
  // 获取用户的所有留言
  getUserComments: (params?: { page?: number; page_size?: number }) =>
    api.get('/user/comments/', { params }),

  // 获取电影留言
  getMovieComments: (movieId: number, params?: { page?: number; page_size?: number }) =>
    api.get(`/movies/${movieId}/comments/`, { params }),

  // 创建留言
  createComment: (movieId: number, content: string) =>
    api.post(`/movies/${movieId}/comments/`, { content }),

  // 更新留言
  updateComment: (commentId: number, content: string) =>
    api.put(`/comments/${commentId}/`, { content }),

  // 删除留言
  deleteComment: (commentId: number) => api.delete(`/comments/${commentId}/`),
}

// 管理员API
export const adminAPI = {
  // 获取统计数据
  getStatistics: () => api.get('/admin/statistics/'),
  
  // 用户管理
  getUsers: (params?: { page?: number; search?: string }) => 
    api.get('/admin/users/', { params }),
  
  // 创建用户
  createUser: (userData: {
    username: string
    email: string
    password: string
    first_name?: string
    last_name?: string
    is_staff?: boolean
    is_active?: boolean
  }) => api.post('/admin/users/', userData),
  
  // 获取用户详情
  getUser: (userId: number) => api.get(`/admin/users/${userId}/`),
  
  // 更新用户
  updateUser: (userId: number, userData: {
    username?: string
    email?: string
    first_name?: string
    last_name?: string
    is_staff?: boolean
    is_active?: boolean
  }) => api.put(`/admin/users/${userId}/`, userData),
  
  // 删除用户
  deleteUser: (userId: number) => api.delete(`/admin/users/${userId}/`),
  
  // 电影管理
  getMovies: (params?: { page?: number; search?: string }) => 
    api.get('/admin/movies/', { params }),
  
  // 创建电影
  createMovie: (movieData: FormData | {
    title: string
    movie_id: string
    genres?: number[]
    year?: number
    director?: string
    description?: string
  }) => {
    const config = movieData instanceof FormData ? {
      headers: { 'Content-Type': 'multipart/form-data' }
    } : {}
    return api.post('/admin/movies/', movieData, config)
  },
  
  // 获取电影详情
  getMovie: (movieId: number) => api.get(`/admin/movies/${movieId}/`),
  
  // 更新电影
  updateMovie: (movieId: number, movieData: FormData | {
    title?: string
    movie_id?: string
    genres?: number[]
    year?: number
    director?: string
    description?: string
  }) => {
    const config = movieData instanceof FormData ? {
      headers: { 'Content-Type': 'multipart/form-data' }
    } : {}
    return api.put(`/admin/movies/${movieId}/`, movieData, config)
  },
  
  // 删除电影
  deleteMovie: (movieId: number) => api.delete(`/admin/movies/${movieId}/`),
  
  // 留言管理
  getComments: (params?: { page?: number; search?: string }) => 
    api.get('/admin/comments/', { params }),
  
  // 删除留言（管理员）
  deleteComment: (commentId: number) => 
    api.delete(`/admin/comments/${commentId}/delete/`),
}